from django.shortcuts import render
from django.views import View
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.contrib.auth.models import User
from common.views.utils import table_api
from django.core.paginator import Paginator
from django.db.models import Q
from ..models.models import UserDept

class UsersView(View):
    @method_decorator(login_required)
    def get(self, request):
        """
        获取用户列表
        :param request:
        :return:
        """
        filters = [] # 筛选条件
        page = int(request.GET.get('page'))
        limit = int(request.GET.get('limit'))
        username = request.GET.get('username')
        email = request.GET.get('email')
        deptId = request.GET.get('deptId')
        if deptId:
            user_ids = UserDept.objects.filter(dept_id=deptId)
            usernames = [user_id.user_id.username for user_id in user_ids]
            filters.append(Q(username__in=usernames))
        if username:
            filters.append(Q(username__contains=username))
        if email:
            filters.append(Q(email__contains=email))
        users = Paginator(User.objects.filter(*filters).order_by('-id'), limit).get_page(page)
        users_dict = [
            {
                'id': user.id,
                'username': user.username,
                'email': user.email,
                'is_active': user.is_active,
                'is_superuser': user.is_superuser,
                'is_staff': user.is_staff,
                'last_login': user.last_login.strftime('%Y-%m-%d %H:%M:%S'),
                'date_joined': user.date_joined.strftime('%Y-%m-%d %H:%M:%S'),
                'dept_name':UsersView.get_user_dept_name(user.id)
            } for user in users
        ]
        return table_api(result=users_dict, total=users.paginator.count)

    @method_decorator(login_required)
    def post(self, request, *args, **kwargs):
        # TODO:
        pass

    @staticmethod
    def get_user_dept_name(user_id):
        """
        获取用户部门
        :param user_id:
        :return:
        """
        try:
            user_dept = UserDept.objects.get(user_id=user_id)
            user_dept_name = user_dept.dept_id.name
            return user_dept_name
        except:
            return ''